<route lang="json5">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '任务变更详情',
    enablePullDownRefresh: false,
    navigationStyle: 'custom',
  },
}
</route>

<template>
  <page-meta :root-font-size="setting.rootFontSize"></page-meta>
  <view style="min-height: 100vh; background-color: #f2f2f1">
    <view style="position: sticky; top: 0; z-index: 9999">
      <wd-navbar
        :title="addType == 'add' ? '新增任务变更' : '任务变更详情'"
        :bordered="false"
        safeAreaInsetTop
      >
        <template #left>
          <wd-icon name="thin-arrow-left" size="22px" color="white" @click="goBack"></wd-icon>
        </template>
      </wd-navbar>
    </view>
    <view
      :style="{
        flex: 1,
        overflow: 'auto',
        paddingBottom:
          form.taskAllStatus == 1 || (form.instanceId && form.status == 1) || form.status == 3
            ? '110rpx'
            : '0',
      }"
    >
      <th-card title="基本信息">
        <th-form>
          <th-form-item label="变更单编号" v-if="addType != 'add'">
            <text class="text">{{ form.changeCode }}</text>
          </th-form-item>
          <th-form-item label="任务单号">
            <text class="text">{{ form.taskCode }}</text>
          </th-form-item>
          <th-form-item label="需求单号">
            <text class="text">{{ form.demandCode }}</text>
          </th-form-item>
          <th-form-item label="任务名称">
            <text class="text">{{ form.projectName }}</text>
          </th-form-item>
          <th-form-item label="原任务负责人" v-if="addType != 'add'">
            <text class="text">{{ form.oldHeadName }}</text>
          </th-form-item>
          <th-form-item label="原任务成员" v-if="addType != 'add'">
            <text class="text">{{ form.oldUserName }}</text>
          </th-form-item>
          <th-form-item label="状态" v-if="addType != 'add'">
            <wd-tag
              :bg-color="getStatus(form.status)['color']"
              :color="getStatus(form.status)['color']"
              plain
              v-if="getStatus(form.status)['label']"
            >
              {{ getStatus(form.status)['label'] }}
            </wd-tag>
            <!-- <text class="text">{{ getStatus(form.status) }}</text> -->
          </th-form-item>
        </th-form>
      </th-card>

      <th-card title="任务人员">
        <taskPerson ref="taskPersonRef" :addType="addType" @selected="setPersonInfo"></taskPerson>
      </th-card>
      <th-card title="审核信息" v-if="form.status > 0 && addType != 'add'">
        <view class="row-list">
          <view class="row" v-if="form.id && form.taskId">
            <!-- <view class="label">审核意见</view> -->
            <view class="value">
              <view class="mb2 mt2">
                <h5>审核意见</h5>
              </view>
              <wd-textarea
                type="textarea"
                v-model="comment"
                rows="6"
                placeholder="请输入审核意见"
                style="border: 1px solid #f7f7f7"
              ></wd-textarea>
            </view>
          </view>
          <view style="margin-top: 10rpx" v-if="form.instanceId">
            <flowTable ref="flowDetailsTableRef" :processInstanceId="form.instanceId"></flowTable>
          </view>
        </view>
      </th-card>
      <!-- <flowTable ref="flowDetailsTableRef" :processInstanceId="form.instanceId"></flowTable> -->
    </view>
    <block v-if="form.taskAllStatus != 2">
      <view class="flow-btn-fixed" v-if="form.id && form.taskId && addType != 'add'">
        <view class="btn_group" style="width: 100%">
          <view class="btn danger" @click="oncomplete(3)">
            <image src="../../../static/reject.png" class="btn-icon"></image>
            拒绝
          </view>
          <view class="btn primary" @click="oncomplete(2)">
            <image src="../../../static/tongyi.png" class="btn-icon"></image>
            同意
          </view>
        </view>
      </view>
      <view class="flow-btn-fixed" v-else>
        <view class="btn_group" style="width: 100%">
          <!-- <view class="btn danger" @click="onCancel()">取消</view> -->
          <view
            class="btn primary"
            @click="onSave()"
            v-if="
              (form.status == 0 || !form.status || form.status == 3 || addType == 'add') &&
              checkPremiss('erp_rdTaskUserChange_view')
            "
          >
            <image src="../../../static/save.png" class="btn-icon"></image>
            保存
          </view>
          <template v-if="addType != 'add'">
            <view
              class="btn primary"
              @click="submit()"
              v-if="
                (form.status == 0 || !form.status || form.status == 3) &&
                checkPremiss('erp_rdTaskUserChange_submit')
              "
            >
              <image src="../../../static/submit.png" class="btn-icon"></image>
              提交
            </view>
            <view
              class="btn primary"
              @click="onRevokeShow()"
              v-if="form.status == 1 && checkPremiss('erp_rdTaskUserChange_revoke')"
            >
              <image src="../../../static/rovoke.png" class="btn-icon"></image>
              撤回
            </view>
          </template>
        </view>
      </view>
    </block>

    <wd-popup v-model="revokeShow" position="bottom" @close="handleClose">
      <view style="display: flex; flex-direction: column; height: 100%">
        <wd-textarea
          v-model="revokeComment"
          placeholder="请填写撤回原因"
          no-border
          prop="revokeComment"
          class="reovke-textarea"
        />
        <view class="flow-btn-fixed">
          <view class="btn_group" style="width: 100%">
            <view class="btn danger" @click="handleClose">取消</view>
            <view class="btn primary" @click="onRevoke">撤回</view>
          </view>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<script lang="ts" setup>
import { useSetting } from '@/stores/setting';
import { getObj, getApplyPerson } from '@/service/pm-task';
import { useUserStore } from '@/stores/user';
import {
  completePersonApply,
  addProjectApplyUsers,
  updateProjectApplyUsers,
  revokeProcessPersonApply,
  submitProcessPersonApply,
} from '@/service/pm-requirement';
import taskPerson from './component/task-person.vue';
import showModal from '@/utils/modal';
import { nextTick } from 'process';
import { useDict } from '@/hooks/dict';
import { useRefresh } from '@/stores/refresh';
const refreshStatus = useRefresh();
const emit = defineEmits(['getData']);
const userStore = useUserStore();
const setting = useSetting();
const personInfo = ref([]);
const comment = ref('');
// 提交表单数据
const form = reactive({
  id: null,
  rdProjectUserEntity: [],
});
const revokeComment = ref('');
const taskPersonRef = ref(null);
const flowDetailsTableRef = ref(null);
const init = (id) => {
  uni.showLoading({
    mask: true,
  });
  getApplyPerson(id)
    .then((res) => {
      if (res.code == 0) {
        for (const key in res.data) {
          console.log(key, 1111111);
          if (Object.prototype.hasOwnProperty.call(res.data, key)) {
            const element = res.data[key];
            form[key] = element;
          }
        }
        if (form.changesDTOS && form.changesDTOS.length) {
          personInfo.value = form.changesDTOS;
        }
        nextTick(() => {
          taskPersonRef.value.init(form);
          if (form.instanceId) {
            flowDetailsTableRef.value.getFlowDetails();
          }
        });
        // form = res.data;
      } else {
        uni.showToast({
          title: '获取详情失败',
          icon: 'none',
        });
      }
    })
    .catch(() => {})
    .finally(() => {
      uni.hideLoading();
      addType.value = 'edit';
    });
};
const getDetail = (options) => {
  getObj(options)
    .then((res) => {
      console.log('res', res);
      // Object.assign(form, res.data);
      try {
        for (const key in res.data) {
          if (Object.prototype.hasOwnProperty.call(res.data, key)) {
            const element = res.data[key];
            form[key] = element;
          }
        }
        if (form.rdProjectUserEntity && form.rdProjectUserEntity.length) {
          personInfo.value = form.rdProjectUserEntity;
          form.changesDTOS = form.rdProjectUserEntity;
        }
        nextTick(() => {
          taskPersonRef.value.init(form);
          // if (form.instanceId) {
          //   flowDetailsTableRef.value.getFlowDetails();
          // }
        });
      } catch (error) {}
    })
    .finally(() => {
      uni.stopPullDownRefresh();
      uni.hideLoading();
    });
};

const statusList = [
  {
    text: '未提交',
    value: '0',
    color: '#108ee9',
  },
  {
    text: '审批中',
    value: '1',
    color: '#d46b08',
  },
  {
    text: '已审核',
    value: '2',
    color: '#87d068',
  },
  {
    text: '驳回',
    value: '3',
    color: '#f50',
  },
  {
    text: '撤回',
    value: '9',
    color: '#f50',
  },
];
const { bill_status } = useDict('bill_status');
const getStatus = (status) => {
  if (status == null)
    return {
      text: '未提交',
      value: '0',
      color: '#108ee9',
    };
  const o1 = statusList.find((item) => item.value == status);
  const o = bill_status.value.find((item) => item.value == status);
  return o
    ? {
        ...o,
        color: o1.color,
      }
    : { text: status };
};
const addType = ref('');
onLoad((options) => {
  addType.value = options.addType;
  if (options.addType == 'add') {
    getDetail(options);
  } else {
    init(options.id);
  }
});
const checkPremiss = (k) => {
  return userStore.userInfos.authBtnList.some((v: string) => v === k);
};
const goBack = () => {
  uni.navigateBack();
};

const oncomplete = (type) => {
  if (type == '3' && !comment.value) {
    uni.showToast({
      title: '请填写审核意见',
      icon: 'none',
      mask: true,
    });
    return;
  }

  const params = {
    // ...form,
    taskId: form.taskId,
    comment: comment.value,
    id: form.id,
    status: type,
  };
  uni.showLoading({
    mask: true,
  });
  completePersonApply(params, form.id)
    .then((res) => {
      if (res.code == 0) {
        uni.showToast({
          title: '单据审核成功',
          icon: 'none',
          mask: true,
        });
        // uni.navigateBack({});
        form.instanceId = '';
        init(form.id);
        refreshStatus.setRefresh(true);

        // nextTick(() => {
        //   flowDetailsTableRef.value.getFlowDetails();
        // });
      } else {
        uni.showToast({
          mask: true,
          title: `单据审核失败，失败原因：${res.msg}`,
          icon: 'none',
        });
      }
    })
    .finally(() => {
      uni.hideLoading();
    });
};

const setPersonInfo = (e) => {
  console.log(e, 123123);

  if (e && e.rdProjectUserEntity && e.rdProjectUserEntity.length) {
    personInfo.value = e.rdProjectUserEntity;
  }
  form.reason = e.reason;
  form.userTime = e.userTime;
  if (addType.value == 'add') {
    form.pid = e.id;
  }
};
const loading = ref(false);
// 保存;
const onSave = async (isSubmit) => {
  // 判断选择时间的时候必须选择 人
  if (personInfo.value.length == 0) {
    uni.showToast({
      title: '请选择人员',
      icon: 'none',
    });

    return;
  }
  if (!form.userTime) {
    uni.showToast({
      title: '请选择预计完成时间',
      icon: 'none',
    });
    return;
  }
  if (loading.value) return;
  loading.value = true;
  const params = personInfo.value.map((item) => {
    if (addType.value == 'add') {
      delete item.id;
    }
    return {
      ...item,
      // id: form.id,
      demandCode: form.demandCode,
      userTime: form.userTime,
      reason: form.reason,
      rdCode: form.taskCode,
    };
  });
  const p = {
    pid: form.pid,
    taskCode: form.taskCode,
    demandId: form.demandId,
    userTime: form.userTime.length > 11 ? form.userTime : form.userTime + ' 00:00:00',
    demandCode: params[0].demandCode,
    reason: form.reason,
    changesDTOS: params,
  } as any;
  if (addType.value != 'add') {
    p.id = form.id;
  }
  uni.showLoading({
    mask: true,
  });
  (addType.value == 'add' ? addProjectApplyUsers : updateProjectApplyUsers)(p)
    .then((res) => {
      loading.value = true;
      if (res.code === 0) {
        if (isSubmit) {
          onSubmit(form);
        } else {
          uni.showToast({
            title: '任务人员保存成功',
            icon: 'none',
          });
          refreshStatus.setRefresh(true);
          setTimeout(() => {
            loading.value = false;
            if (addType.value == 'add') {
              init(res.data.id);
            } else {
              init(form.id);
            }
          }, 1000);
        }
        // uni.$emit('refresh');
        emit('getData');
      } else {
        uni.showToast({
          title: `任务人员保存失败， 失败原因：${res.msg}`,
          icon: 'none',
        });
        loading.value = false;
        // notification.error({
        //   message: '提示',
        //   description: `任务人员保存失败， 失败原因：${res.msg}`,
        //   placement: 'bottomRight',
        // });
      }
    })
    .catch((err) => {
      uni.showToast({
        title: `任务人员保存失败， 失败原因：${err.msg || err}`,
        icon: 'none',
      });
      loading.value = false;
      // notification.error({
      //   message: '提示',
      //   description: `任务人员保存失败， 失败原因：${err.msg || err}`,
      //   placement: 'bottomRight',
      // });
    })
    .finally(() => {
      uni.hideLoading();
      // loading.value = false;
    });
};
const onSubmit = async (row) => {
  try {
    const res = await submitProcessPersonApply({ id: row.id });

    if (res.code === 0) {
      uni.showToast({
        title: `单据提交成功`,
        icon: 'none',
      });
      // notification.success({
      //   message: '提示',
      //   description: `单据${row.demandCode}提交成功`,
      //   placement: 'bottomRight',
      // });
      refreshStatus.setRefresh(true);
      setTimeout(() => {
        loading.value = false;
        init(form.id);
      }, 1000);
    } else {
      uni.showToast({
        title: `单据提交失败, 失败原因: ${res.msg}`,
        icon: 'none',
      });
    }
  } catch (err: any) {
    uni.showToast({
      title: `单据提交失败, 失败原因: ${err.msg}`,
      icon: 'none',
    });
  }
};
// 提交审核
const submit = async (row = form) => {
  // try {
  //   await useMessageBox().confirm(t('common.optConfirmText'));
  // } catch {
  //   return;
  // }
  uni.showModal({
    title: '提示',
    content: '确定保存并提交审核吗?',
    cancelText: '取消',
    confirmText: '确定',
    success: async (res) => {
      if (res.confirm) {
        onSave(true);
      } else {
        loading.value = false;
      }
    },
    complete: () => {
      setTimeout(() => {
        loading.value = false;
      }, 500);
    },
  });

  // state.loading = true;
};
// 显示撤回原因
const revokeShow = ref(false);
const onRevokeShow = () => {
  revokeShow.value = true;
};
const handleClose = () => {
  revokeShow.value = false;
};
const onRevoke = () => {
  showModal({
    title: '提示',
    content: '是否撤回该单据',
    showCancel: true,
    confirm: () => {
      uni.showLoading({
        mask: true,
      });
      revokeProcessPersonApply({
        id: form.id,
        instanceId: form.instanceId,
        comment: revokeComment.value,
      })
        .then((res) => {
          if (res.code == 0) {
            uni.showToast({
              mask: true,
              title: `单据${form.demandCode}撤回成功`,
              icon: 'none',
            });
            refreshStatus.setRefresh(true);
            // uni.$emit('refresh');
            handleClose();
            init(form.id);
          } else {
            uni.showToast({
              mask: true,
              title: `单据${form.demandCode}撤回失败，失败原因：${res.msg}`,
              icon: 'none',
            });
          }
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
  });
};
</script>

<style lang="scss" scoped>
@import '../experiment/components/table';

.block .content {
  padding: 0 !important;
}

.card-detail {
  padding: 0 !important;
}

.wd-cell {
  padding-left: 0 !important;
}

.wd-card__title {
  border-left: 4px solid #2e5cf6 !important;
}

.pm-table {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  padding: 0 30rpx;

  .pm-title {
    box-sizing: border-box;
    padding-left: 20rpx;
    margin: 40rpx 0;
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    border-left: 8rpx solid #2e5cf6;
    border-radius: 4rpx;
  }

  .pm-row {
    display: flex;
    min-height: 60rpx;
    border-bottom: 1px solid #f6f0f0;

    .pm-label {
      display: flex;
      align-items: center;
      width: 20%;
      font-size: 26rpx;
      color: #979494;
    }

    .pm-value {
      display: flex;
      flex: 1;
      align-items: center;
      font-size: 26rpx;
      color: #333;
    }
  }
}

.sign-main {
  // display: flex;
  // align-items: center;
  // justify-content: center;
  // width: 100%;
  // margin: 20rpx 0;
  position: fixed;
  right: 0rpx;
  bottom: 40rpx;
  width: 160rpx;
  height: 80rpx;
  line-height: 80rpx;
  color: white;
  text-align: center;
  background-color: rgb(77 128 240);

  // border-radius: 50%;
  border-top-left-radius: 40rpx;
  border-bottom-left-radius: 40rpx;
}

:deep(.label) {
  width: 160rpx !important;
}

.result-tag {
  padding: 6rpx 14rpx;
  margin: 2rpx 0;
  font-size: 24rpx;
  color: white;
  background-color: #87d068;
  border-radius: 4rpx;
}

.sign-main-show {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  .sign-main-show-title {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 80rpx;
    margin-bottom: 20rpx;
    font-size: 30rpx;
    font-weight: bold;
    color: #818181;
    border-bottom: 1px solid #e3e3e3;
  }

  .sign-main-show-line {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 90%;
    padding: 20rpx;
    margin: 20rpx 0;
    border: 4rpx solid #d0dbff;
    border-radius: 10rpx;
  }

  .sign-main-show-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 80rpx;
    border-top: 1px solid #e3e3e3;
  }
}

.info-list {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.info-list-main {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  width: 100%;
  padding: 10rpx;
  margin: 10rpx 0;
  border: 1px solid #e3e3e3;
  border-radius: 8rpx;

  .info-list-row {
    display: flex;
    width: 100%;

    .info-list-label {
      width: 150rpx;
      font-size: 28rpx;
      color: #808080;
    }

    .info-list-value {
      display: flex;
      flex: 1;
      align-items: center;
      width: 0;
      word-break: break-all;
      white-space: pre-line;
    }
  }
}

.craft-row {
  display: flex;
  align-items: center;

  .craft-row-img-main {
    display: flex;
    flex: 1;
    align-items: center;
    justify-content: center;
    width: 0;
  }
}

.craft-row-img {
  width: 240rpx;
  height: 240rpx;
}

.form-demandDesc {
  align-items: flex-start !important;

  .text {
    word-break: break-all;
  }
}

.info-row-item {
  padding: 6rpx 0;
  word-break: break-all;

  // border-bottom: 1px solid #f2f2f2;
}

.text {
  word-break: break-all;
  word-wrap: break-word;
}

:deep(.wd-collapse-item__body) {
  padding: 0 !important;
}

// :deep(.wd-collapse-item__wrapper){
//   height:auto !important;
// }

:deep(.wd-collapse-item__body) {
  padding: 10rpx;
}

:deep(.wd-collapse-item__header) {
  padding-right: 10rpx;
  padding-left: 10rpx;
}

.flow-btn-fixed {
  width: 100%;
  background-color: white;
  border-top: 1px solid #f2f2f1;
  position: fixed;
  bottom: 0;
  z-index: 10;
}

.btn_group {
  display: flex;
  justify-content: space-between;

  // margin: 0rpx 0 20rpx;
  // border-bottom: 1px solid #f2f2f1;

  .btn {
    display: flex;

    // width: 49%;
    flex: 1;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    // height: 40px;
    min-height: 40px;
    padding: 10rpx 0;
    font-size: 24rpx;
    color: black;

    // background-color: white !important;
    background-color: #dbecff !important;
    border-left: 1px solid #f7f7f7;
    border-radius: 0 !important;

    // color: white;
    border-radius: 6rpx;

    .btn-icon {
      width: 40rpx;
      height: 40rpx;
      margin-bottom: 8rpx;
    }
  }

  .danger {
    background-color: #f56c6c;
  }

  .primary {
    background-color: #409eff;
  }
}

.form-demandDesc {
  align-items: flex-start !important;
}

:deep(.wd-navbar__left--hover) {
  background: none !important;
}
</style>
